package com.hwadeefsc.springboot.controller;

import com.hwadeefsc.springboot.entity.Users;
import com.hwadeefsc.springboot.service.LoginService;
import com.hwadeefsc.springboot.utils.result.DataResult;
import com.hwadeefsc.springboot.utils.result.code.Code;
import com.hwadeefsc.springboot.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("login")
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("login")
    public DataResult loginUser(@RequestBody Users user) {
        LoginUserVo loginUserVo = loginService.loginUser(user);

        if (loginUserVo == null) {
            return DataResult.errByErrCode(Code.LOGIN_ERROR);
        }
        return DataResult.successByData(loginUserVo);
    }

    @RequestMapping("logout")
    public DataResult logout(HttpServletRequest request) {
        //1.获取请求头里的token
        String token = request.getHeader("Token");
        //2.删除在redis里面的token
        redisTemplate.delete("Token::" + token);
        return DataResult.succ();
    }
}